package concurrecy;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class LiftOff implements Runnable {
    private static int count = 0;
    private final int id = count ++;
    private int countDown = 10;

    @Override
    public String toString() {
        return String.format("#{%d} (%d)", id, countDown);
    }

    @Override
    public void run() {
        Random random = new Random();
        while(countDown -- > 0) {
            System.out.println(this);
//            Thread.yield();
            try {
                TimeUnit.MILLISECONDS.sleep(random.nextInt(100));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("#{%d} fired\n", id);
    }
}

public class Test {
    public static void main(String[] args) {
//        for (int i = 0; i < 5; i++) {
//            new Thread(new LiftOff()).start();
//        }
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            executorService.execute(new LiftOff());
        }
        executorService.shutdown();
    }
}
